<template>
    <div class="wrapper">
     <header>
		<div class="icon-location-box">
		  <div class="icon-location"></div>
		</div>
		<div class="location-text">
		  天津大学 47教第六机房<i class="fa fa-caret-down"></i>
		</div>
		
		<!-- 商家入口按钮 -->
		<!-- 已移除商家入口按钮，将其转移到"我的"页面 -->
		
		<!-- 用户信息显示 -->
		<div class="user-info" v-if="isLoggedIn" @click="goToUserInfo">
		  <div class="user-avatar">
			<i class="fa fa-user"></i>
		  </div>
		  <div class="user-name">{{ userInfo.username || '用户' }}</div>
		</div>
		<!-- 未登录时显示登录按钮 -->
		<div class="login-btn" v-else @click="goToLogin">
		  <i class="fa fa-sign-in"></i>
		  <span>登录</span>
		</div>
	  </header>
  
	  <div class="search">
		<div class="search-fixed-top" ref="fixedBox">
		  <div class="search-box">
			<i class="fa fa-search"></i>搜索饿了么商家、商品名称
		  </div>
		</div>
	  </div>
  
	  <ul class="foodtype">
		<li @click="toBusinessList(1)">
		  <img src="../assets/dcfl01.png" />
		  <p>美食</p>
		</li>
		<li @click="toBusinessList(2)">
		  <img src="../assets/dcfl02.png" />
		  <p>早餐</p>
		</li>
		<li @click="toBusinessList(3)">
		  <img src="../assets/dcfl03.png" />
		  <p>跑腿代购</p>
		</li>
		<li @click="toBusinessList(4)">
		  <img src="../assets/dcfl04.png" />
		  <p>汉堡披萨</p>
		</li>
		<li @click="toBusinessList(5)">
		  <img src="../assets/dcfl05.png" />
		  <p>甜品饮品</p>
		</li>
		<li @click="toBusinessList(6)">
		  <img src="../assets/dcfl06.png" />
		  <p>速食简餐</p>
		</li>
		<li @click="toBusinessList(7)">
		  <img src="../assets/dcfl07.png" />
		  <p>地方小吃</p>
		</li>
		<li @click="toBusinessList(8)">
		  <img src="../assets/dcfl08.png" />
		  <p>米粉面馆</p>
		</li>
		<li @click="toBusinessList(9)">
		  <img src="../assets/dcfl09.png" />
		  <p>包子粥铺</p>
		</li>
		<li @click="toBusinessList(10)">
		  <img src="../assets/dcfl10.png" />
		  <p>炸鸡炸串</p>
		</li>
	  </ul>
  
	  <div class="banner">
		<h3>品质套餐</h3>
		<p>搭配齐全吃得好</p>
		<a>立即抢购 &gt;</a>
	  </div>
  
	  <div class="supermember" @click="toSuperMember" style="cursor: pointer;" :class="{ 'is-svip': isSvip }">
          <div class="left">
            <img src="../assets/super_member.png" />
            <h3>超级会员</h3>
            <p v-if="!isSvip">&#8226; 每月享超值权益</p>
            <p v-else>&#8226; 尊享3000元花呗额度</p>
          </div>
          <div class="right">{{ svipText }}</div>
      </div>
  
      <div class="recommend">
        <div class="recommend-line"></div>
        <p>推荐商家</p>
        <div class="recommend-line"></div>
      </div>


      <ul class="recommendtype">
        <li 
          :class="{ active: sortType === 'rating' }"
          @click="sortBusinessBy('rating')"
        >
          综合排序
        </li>
        <li 
          :class="{ active: sortType === 'distance' }"
          @click="sortBusinessBy('distance')"
        >
          距离最近
        </li>
        <li 
          :class="{ active: sortType === 'sales' }"
          @click="sortBusinessBy('sales')"
        >
          销量最高
        </li>
      </ul>
  
      <ul class="business">
        <li 
          v-for="business in businessList" 
          :key="business.id"
          @click="goToBusiness(business.id)"
        >
          <img :src="getBusinessImage(business.id)" @error="handleImageError($event, business.id)" />
          <div class="business-info">
            <div class="business-info-h">
              <h3>{{ business.businessName }}</h3>
              <div class="business-info-like">&#8226;</div>
            </div>
            <div class="business-info-star">
              <div class="business-info-star-left">
                <i class="fa fa-star"></i>
                <i class="fa fa-star"></i>
                <i class="fa fa-star"></i>
                <i class="fa fa-star"></i>
                <i class="fa fa-star"></i>
                <p>{{ business.rating }} 月售{{ business.monthlySales }}单</p>
              </div>
              <div class="business-info-star-right">蜂鸟专送</div>
            </div>
            <div class="business-info-delivery">
                <p>&#165;{{ business.startPrice }}起送 | &#165;{{ business.deliveryPrice }}配送</p>
                <p>{{ business.distance }}km | {{ getDeliveryTime(business.distance) }}分钟</p>
            </div>
            <div class="business-info-explain" v-if="isLoggedIn">
              <div>{{ business.businessExplain }}</div>
            </div>
            <div class="business-info-explain" v-else>
              <div style="color: #999; font-style: italic;">登录后查看菜品信息</div>
            </div>
            <div class="business-info-promotion">
              <div class="business-info-promotion-left">
                <div class="business-info-promotion-left-incon">新</div>
                <p>饿了么新用户首单立减9元</p>
              </div>
              <div class="business-info-promotion-right">
                <p>2个活动</p>
                <i class="fa fa-caret-down"></i>
              </div>
            </div>
            <div class="business-info-promotion">
              <div class="business-info-promotion-left">
                <div
                  class="business-info-promotion-left-incon"
                  style="background-color: #f1884f"
                >
                  特
                </div>
                <p>特价商品5元起</p>
              </div>
            </div>
          </div>
        </li>
      </ul>
  
      <Footer></Footer>
    </div>
</template>
  
<script setup>
  import Footer from "../components/Footer.vue";
  import { ref, onMounted, onUnmounted, computed } from "vue";
  import { useRouter } from "vue-router";
  import { storeToRefs } from 'pinia'; // 导入 storeToRefs
  import { useUserStore } from '@/store/pinia_store_user'; // 导入 User Store
  import { businessApi, walletApi } from "../api/index.js";// 导入 Business API 和 Wallet API
  import sj01 from '@/assets/sj01.png'
  import sj02 from '@/assets/sj02.png'
  import sj03 from '@/assets/sj03.png'
  import sj04 from '@/assets/sj04.png'
  import sj05 from '@/assets/sj05.png'
  import sj06 from '@/assets/sj06.png'
  import sj07 from '@/assets/sj07.png'

  const router = useRouter();
  const fixedBox = ref(null);
  
  // 使用 Pinia Store 作为唯一的状态来源
  const userStore = useUserStore();
  const { userInfo } = storeToRefs(userStore); // 保持响应性
  
  // 计算属性：检查用户是否登录
  const isLoggedIn = computed(() => {
    return !!localStorage.getItem('jwt-token');
  });

  // 获取用户名或使用默认值
  const username = computed(() => {
    return userInfo.value?.username || '用户';
  });
  
  // 判断是否为SVIP会员
  const isSvip = computed(() => {
    return walletInfo.value?.isActiveSvip === true;
  });
  
  // SVIP显示文本
  const svipText = computed(() => {
    return isSvip.value ? '超级会员 ✓' : '立即开通 >';
  });

  // 商家列表和排序状态
  const businessList = ref([]);
  const sortType = ref('rating');
  
  // 钱包信息
  const walletInfo = ref(null);

  // --- 生命周期钩子 ---
  onMounted(() => {
    document.onscroll = () => {
        let s1 = document.documentElement.scrollTop;
        let s2 = document.body.scrollTop;
        let scroll = s1 == 0 ? s2 : s1;
        let width = document.documentElement.clientWidth;
        let search = fixedBox.value;
        if (scroll > width * 0.12) {
            search.style.position = "fixed";
            search.style.left = "0";
            search.style.top = "0";
        } else {
            search.style.position = "static";
        }
    };
    
    // 初始化业务数据
    initBusinessList();
    
    // 在组件挂载时检查用户状态
    checkUserState();
  });

  onUnmounted(() => {
    document.onscroll = null;
  });
  
  // 检查用户状态，如果有token但没有用户信息，尝试重新获取
  const checkUserState = async () => {
    if (isLoggedIn.value && (!userInfo.value || Object.keys(userInfo.value).length === 0)) {
      try {
        await userStore.fetchUserInfo();
        console.log('用户信息已重新加载:', userInfo.value);
      } catch (error) {
        console.error('自动加载用户信息失败:', error);
      }
    }
    
    // 如果用户已登录，获取钱包信息
    if (isLoggedIn.value) {
      await loadWalletInfo();
    }
  };
  
  // 获取钱包信息
  const loadWalletInfo = async () => {
    try {
      const wallet = await walletApi.getMyWallet();
      walletInfo.value = wallet;
      console.log('钱包信息已加载:', wallet);
    } catch (error) {
      console.error('加载钱包信息失败:', error);
      // 如果钱包不存在，可以静默失败
      walletInfo.value = null;
    }
  };

  // --- API 调用 ---
  const initBusinessList = async () => {
      // 页面加载时，默认按评分排序
      await sortBusinessBy('rating');
  }

  const sortBusinessBy = async (type) => {
      // 如果排序类型未变且已有数据，则不重复请求
      if (sortType.value === type && businessList.value.length > 0) return;
      sortType.value = type;

      try {
          console.log(`正在按 '${type}' 排序加载商家列表...`);
          // [修正] 调用新的、统一的 API 函数
          // 我将假设你的后端 /businesses 接口支持一个名为 sortBy 的查询参数
          const response = await businessApi.getBusinessList({ sortBy: type });
          businessList.value = response;
          console.log("商家列表加载成功:", response);
      } catch (error) {
          console.error('首页加载商家列表失败:', error);
          alert('加载商家信息失败，请检查网络或稍后重试。');
      }
  }

  // --- 辅助函数 ---
  const getBusinessImage = (id) => {
      // 优先使用后端图片API获取商家上传的图片
      // 使用商家图片二进制数据API端点
      const apiBaseUrl = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080';
      // 添加时间戳参数，避免浏览器缓存
      const timestamp = new Date().getTime();
      const backendImageUrl = `${apiBaseUrl}/api/images/business-binary/${id}?t=${timestamp}`;
      
      // 返回后端URL，并通过onerror处理图片加载失败的情况
      return backendImageUrl;
  }

  // 处理图片加载失败，使用预存的静态图片
  const handleImageError = (event, businessId) => {
      console.warn(`商家图片加载失败，使用默认图片: businessId=${businessId}`);
      const imageMap = {
          1: sj01, 2: sj02, 3: sj03, 4: sj04,
          5: sj05, 6: sj06, 7: sj07
      };
      event.target.src = imageMap[businessId] || sj01;
  }

  const getDeliveryTime = (distance) => {
      if (!distance || distance <= 0) return 20;
      if (distance <= 2) return Math.round(20 + (distance - 1) * 6);
      if (distance <= 5) return Math.round(26 + (distance - 2) * 4);
      if (distance <= 8) return Math.round(38 + (distance - 5) * 2);
      return Math.round(44 + Math.min(distance - 8, 2) * 1.5);
  }

  // --- 导航函数 ---
  const toBusinessList = (orderTypeId) => {
      router.push({ path: "/businessList", query: { orderTypeId: orderTypeId } });
  };

  const goToBusiness = (businessId) => {
      router.push({ path: '/businessInfo', query: { businessId } });
  }

  const toSuperMember = () => {
      // 直接跳转到我的钱包页面
      router.push('/wallet');
  };

  const goToUserInfo = () => {
      router.push({ path: '/userInfo' });
  };

  const goToLogin = () => {
      router.push({ path: '/login' });
  };

  // 已移除goToBusinessLogin方法，因为入口已转移到"我的"页面
</script>

<style scoped>
  /* 你的CSS样式是正确的，这里省略以保持简洁 */
  /****************** 总容器 ******************/
  .wrapper {
    width: 100%;
    height: 100%;
  }
  
  /****************** header ******************/
  .wrapper header {
    width: 100%;
    height: 12vw;
    background-color: #0097ff;
  
    display: flex;
    align-items: center;
  }
  
  .wrapper header .icon-location-box {
    width: 3.5vw;
    height: 3.5vw;
    margin: 0 1vw 0 3vw;
  }
  
  .wrapper header .location-text {
    font-size: 4.5vw;
    font-weight: 700;
    color: #fff;
  }
  
  .wrapper header .location-text .fa-caret-down {
    margin-left: 1vw;
  }

  /* 用户信息样式 */
  .wrapper header .user-info {
    margin-left: auto;
    margin-right: 3vw;
    display: flex;
    align-items: center;
    cursor: pointer;
    color: #fff;
  }

  .wrapper header .user-info .user-avatar {
    width: 8vw;
    height: 8vw;
    border-radius: 50%;
    background-color: rgba(255, 255, 255, 0.2);
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 2vw;
  }

  .wrapper header .user-info .user-avatar .fa-user {
    font-size: 4vw;
  }

  .wrapper header .user-info .user-name {
    font-size: 3.5vw;
    font-weight: 500;
  }

  /* 登录按钮样式 */
  .wrapper header .login-btn {
    margin-left: auto;
    margin-right: 3vw;
    display: flex;
    align-items: center;
    cursor: pointer;
    color: #fff;
    background-color: rgba(255, 255, 255, 0.2);
    padding: 2vw 4vw;
    border-radius: 4vw;
  }

  .wrapper header .login-btn .fa-sign-in {
    font-size: 3.5vw;
    margin-right: 1vw;
  }

  .wrapper header .login-btn span {
    font-size: 3.5vw;
    font-weight: 500;
  }

  /* 商家入口按钮样式 */
  .wrapper header .business-entry-btn {
    margin-left: auto;
    margin-right: 2vw;
    display: flex;
    align-items: center;
    cursor: pointer;
    color: #fff;
    background-color: rgba(255, 255, 255, 0.15);
    padding: 1.5vw 3vw;
    border-radius: 3vw;
    border: 1px solid rgba(255, 255, 255, 0.3);
    transition: all 0.3s ease;
  }

  .wrapper header .business-entry-btn:hover {
    background-color: rgba(255, 255, 255, 0.25);
  }

  .wrapper header .business-entry-btn .fa-store {
    font-size: 3vw;
    margin-right: 1vw;
  }

  .wrapper header .business-entry-btn span {
    font-size: 3vw;
    font-weight: 500;
  }
  
  /****************** search ******************/
  .wrapper .search {
    width: 100%;
    height: 13vw;
  }
  
  .wrapper .search .search-fixed-top {
    width: 100%;
    height: 13vw;
    background-color: #0097ff;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  
  .wrapper .search .search-fixed-top .search-box {
    width: 90%;
    height: 9vw;
    background-color: #fff;
    border-radius: 2px;
  
    display: flex;
    justify-content: center;
    align-items: center;
  
    font-size: 3.5vw;
    color: #aeaeae;
    font-family: "宋体";
    /*此样式是让文本选中状态无效*/
    user-select: none;
  }
  
  .wrapper .search .search-fixed-top .search-box .fa-search {
    margin-right: 1vw;
  }
  
  /****************** 点餐分类部分 ******************/
  .wrapper .foodtype {
    width: 100%;
    height: 48vw;
  
    display: flex;
    flex-wrap: wrap;
    justify-content: space-around;
    /*要使用align-content。10个子元素将自动换行为两行，而且两行作为一个整体垂直居中*/
    align-content: center;
  }
  
  .wrapper .foodtype li {
    /*一共10个子元素，通过计算，子元素宽度在16.7 ~ 20 之间，才能保证换两行*/
    width: 18vw;
    height: 20vw;
  
    display: flex;
    /*弹性盒子主轴方向设为column，然后仍然是垂直水平方向居中*/
    flex-direction: column;
    justify-content: center;
    align-items: center;
  
    user-select: none;
    cursor: pointer;
  }
  
  .wrapper .foodtype li img {
    width: 12vw;
    /*视频讲解时高度设置为12vw，实际上设置为10.3vw更佳*/
    height: 10.3vw;
  }
  
  .wrapper .foodtype li p {
    font-size: 3.2vw;
    color: #666;
  }
  
  /****************** 横幅广告部分 ******************/
  .wrapper .banner {
    /**
           * 设置容器宽度95%，然后水平居中，这样两边留白; 
           * 这里不能用padding，因为背景图片也会覆盖padding
           */
    width: 95%;
    margin: 0 auto;
    height: 29vw;
  
    /*此三个样式组合，可以保证背景图片充满整个容器*/
    background-image: url(../assets/index_banner.png);
    background-repeat: no-repeat;
    background-size: cover;
  
    box-sizing: border-box;
    padding: 2vw 6vw;
  }
  
  .wrapper .banner h3 {
    font-size: 4.2vw;
    margin-bottom: 1.2vw;
  }
  
  .wrapper .banner p {
    font-size: 3.4vw;
    color: #666;
    margin-bottom: 2.4vw;
  }
  
  .wrapper .banner a {
    font-size: 3vw;
    color: #c79060;
    font-weight: 700;
  }
  
  /****************** 超级会员部分 ******************/
  .wrapper .supermember {
    /*这里也设置容器宽度95%，不能用padding，因为背景色也会充满padding*/
    width: 95%;
    margin: 0 auto;
    height: 11.5vw;
    background-color: #feedc1;
    margin-top: 1.3vw;
    border-radius: 2px;
    color: #644f1b;
  
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .wrapper .supermember .left {
    display: flex;
    align-items: center;
    margin-left: 4vw;
    user-select: none;
  }
  
  .wrapper .supermember .left img {
    width: 6vw;
    height: 6vw;
    margin-right: 2vw;
  }
  
  .wrapper .supermember .left h3 {
    font-size: 4vw;
    margin-right: 2vw;
  }
  
  .wrapper .supermember .left p {
    font-size: 3vw;
  }
  
  .wrapper .supermember .right {
    font-size: 3vw;
    margin-right: 4vw;
    cursor: pointer;
  }
  
  /* SVIP状态样式 */
  .wrapper .supermember.is-svip {
    background: linear-gradient(135deg, #FFD700 0%, #FFA500 100%);
    color: #fff;
  }
  
  .wrapper .supermember.is-svip .right {
    font-weight: bold;
  }
  
  /****************** 推荐商家部分 ******************/
  .wrapper .recommend {
    width: 100%;
    height: 14vw;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  
  .wrapper .recommend .recommend-line {
    width: 6vw;
    height: 0.2vw;
    background-color: #888;
  }
  
  .wrapper .recommend p {
    font-size: 4vw;
    margin: 0 4vw;
  }
  
  /****************** 推荐方式部分（修改为排序功能） ******************/
  .wrapper .recommendtype {
    width: 100%;
    height: 5vw;
    margin-bottom: 5vw;
  
    display: flex;
    justify-content: space-around;
    align-items: center;
  }
  
  .wrapper .recommendtype li {
    font-size: 3.5vw;
    color: #555;
    cursor: pointer;
    transition: all 0.3s ease;
    padding: 1vw 2vw;
    border-radius: 2vw;
  }

  /* 新增：排序激活状态样式 */
  .wrapper .recommendtype li.active {
    color: #0097ff;
    background-color: rgba(0, 151, 255, 0.1);
    font-weight: bold;
  }

  .wrapper .recommendtype li:hover {
    background-color: #f5f5f5;
  }
  
  /****************** 推荐商家列表部分 ******************/
  .wrapper .business {
    width: 100%;
    margin-bottom: 14vw;
  }
  
  .wrapper .business li {
    width: 100%;
    box-sizing: border-box;
    padding: 2.5vw;
    user-select: none;
    border-bottom: solid 1px #ddd;
    cursor: pointer; /* 新增：鼠标指针样式 */
  
    display: flex;
  }

  /* 新增：商家项hover效果 */
  .wrapper .business li:hover {
    background-color: #f9f9f9;
  }
  
  .wrapper .business li img {
    width: 18vw;
    height: 18vw;
  }
  
  .wrapper .business li .business-info {
    width: 100%;
    box-sizing: border-box;
    padding-left: 3vw;
  }
  
  .wrapper .business li .business-info .business-info-h {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 2vw;
  }
  
  .wrapper .business li .business-info .business-info-h h3 {
    font-size: 4vw;
    color: #333;
  }
  
  .wrapper .business li .business-info .business-info-h .business-info-like {
    width: 1.6vw;
    height: 3.4vw;
    background-color: #666;
    color: #fff;
    font-size: 4vw;
    margin-right: 4vw;
  
    display: flex;
    justify-content: center;
    align-items: center;
  }
  
  .wrapper .business li .business-info .business-info-star {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 2vw;
    font-size: 3.1vw;
  }
  
  .wrapper
    .business
    li
    .business-info
    .business-info-star
    .business-info-star-left {
    display: flex;
    align-items: center;
  }
  
  .wrapper
    .business
    li
    .business-info
    .business-info-star
    .business-info-star-left
    .fa-star {
    color: #fec80e;
    margin-right: 0.5vw;
  }
  
  .wrapper
    .business
    li
    .business-info
    .business-info-star
    .business-info-star-left
    p {
    color: #666;
    margin-left: 1vw;
  }
  
  .wrapper
    .business
    li
    .business-info
    .business-info-star
    .business-info-star-right {
    background-color: #0097ff;
    color: #fff;
    font-size: 2.4vw;
    border-radius: 2px;
    padding: 0 0.6vw;
  }
  
  .wrapper .business li .business-info .business-info-delivery {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 2vw;
  
    color: #666;
    font-size: 3.1vw;
  }
  
  .wrapper .business li .business-info .business-info-explain {
    display: flex;
    align-items: center;
    margin-bottom: 3vw;
  }
  
  .wrapper .business li .business-info .business-info-explain div {
    border: solid 1px #ddd;
    font-size: 2.8vw;
    color: #666;
    border-radius: 3px;
    padding: 0 0.1vw;
  }
  
  .wrapper .business li .business-info .business-info-promotion {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 1.8vw;
  }
  
  .wrapper
    .business
    li
    .business-info
    .business-info-promotion
    .business-info-promotion-left {
    display: flex;
    align-items: center;
  }
  
  .wrapper
    .business
    li
    .business-info
    .business-info-promotion
    .business-info-promotion-left
    .business-info-promotion-left-incon {
    width: 4vw;
    height: 4vw;
    background-color: #70bc46;
    border-radius: 3px;
    font-size: 3vw;
    color: #fff;
  
    display: flex;
    justify-content: center;
    align-items: center;
  }
  
  .wrapper
    .business
    li
    .business-info
    .business-info-promotion
    .business-info-promotion-left
    p {
    color: #666;
    font-size: 3vw;
    margin-left: 2vw;
  }
  
  .wrapper
    .business
    li
    .business-info
    .business-info-promotion
    .business-info-promotion-right {
    display: flex;
    align-items: center;
    font-size: 2.5vw;
    color: #999;
  }
  
  .wrapper
    .business
    li
    .business-info
    .business-info-promotion
    .business-info-promotion-right
    p {
    margin-right: 2vw;
  }
</style>